<template>
  <div class="user-create">
    <el-page-header class="page-head" @back="$router.back()" title="所有用户">
      <template #content>
        <span style="font-weight: 600;">添加用户</span>
      </template>
    </el-page-header>
    <el-form
    label-position="right"
    label-width="120px"
    style="max-width: 800px">
      <el-form-item label="账号">
        <el-input v-model="form.account" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" show-password />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="身份">
        <el-select v-model="form.rid">
          <el-option v-for="role in roles"
          :key="role.id"
          :label="role.name"
          :value="role.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :disabled="!formSubmitEnable">创建</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { post } from '../../../utils/common/api'
import { hashPassword } from '../../../utils/user'

export default {
  data() {
    return {
      form: {
        account: '',
        password: '',
        name: '',
        rid: 1
      },

      formSubmitEnable: true,

      roles: []
    }
  },

  methods: {
    onSubmit() {
      var that = this
      that.formSubmitEnable = false
      var form = JSON.parse(JSON.stringify(that.form))
      form.password = hashPassword(form.password)
      post('/user/create', form).then(function(res) {
        ElNotification({
          title: '用户创建成功',
          message: `您刚刚创建了用户 ${res.name} ，账号 ${res.account}`,
          type: 'success',
          position: 'bottom-right',
        })
        that.$router.back()
      }).finally(function() {
        that.formSubmitEnable = true
      })
    }
  },

  mounted() {
    var that = this
    post('/user/role/all', {}).then(function(res) {
      that.roles = res.list
    })
  }
}
</script>

<style scoped>
.page-head {
  margin-bottom: 40px;
}
</style>